import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, Tabs } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import KeepAlive, { AliveScope } from 'react-activation'
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiStockTakeListPage, apiStockTakeListDel, apiStockTakeListAddBefore, apiStockLibraryGoodsPage, apiStockLibraryGoodsList, apiStockLibraryGoodsDetilList } from '@/request/storageManager/stock.js'
import { exportSheetTable } from '@/utils/exportTable'
import './components/style.scss'
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"

const { TabPane } = Tabs;
const { Option } = Select
const status = [{ label: '草稿', value: 0 }, { label: '未审核', value: 1 }, { label: '已审核', value: 2 }, { label: '已驳回', value: 3 }]

class Stock extends Component {
    constructor() {
        super()
        // this.formRef_check = React.createRef()
        // this.formRef_store = React.createRef()
        this.queryFormRef_check = React.createRef()
        this.queryFormRef_store = React.createRef()
        this.state = {
            defaultActiveKey: '1',
            columns: [
                {
                    title: "仓库名称",
                    dataIndex: "libraryName",
                    key: "libraryName",

                },
                {
                    title: "物品编码",
                    dataIndex: "goodsSkuNo",
                    key: "goodsSkuNo",

                },
                {
                    title: "物品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",

                },
                {
                    title: "规格",
                    dataIndex: "sku",
                    key: "sku",

                },

                {
                    title: "库存下限",
                    dataIndex: "minCount",
                    key: "minCount",
                    render: (text) => {
                        if (text == -1) {
                            return '不限制'
                        }
                        return text
                    }
                },
                {
                    title: "库存量",
                    dataIndex: "count",
                    key: "count",

                },
                {
                    title: "待出库",
                    dataIndex: "waiteOutCount",
                    key: "waiteOutCount",

                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:stockStore:view']} onClick={() => this.goGoods(render.id)}>查看详情</TheButton>
                        </div>
                    }
                },
            ],
            newColumns_store: [],
            form_show_store: true,
            searchOption_store: [
                { field: 'libraryId', label: '仓库名称', placeholder: '请选择仓库名称', required: false, rules: [], type: 'Select', api: apiStockTakeListAddBefore, txt: 'name', value: 'id', options: [], defaultValue: '' },
                { field: 'goodsSkuNo', label: '物品编码', placeholder: '请输入物品编码', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'goodsName', label: '物品名称', placeholder: '请输入物品名称', required: false, rules: [], type: 'Input', defaultValue: '' },

            ],
            queryForm_store: {},
            dataSource: [],
            columnsCheck: [
                {
                    title: "盘点单号",
                    dataIndex: "code",
                    key: "code",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "盘点日期",
                    dataIndex: "createTime",
                    key: "createTime",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "仓库名称",
                    dataIndex: "libraryName",
                    key: "libraryName",
                    render: (text, render) => {
                        return text
                    }
                },
                // {
                //     title: "盈亏量",
                //     dataIndex: "sum",
                //     key: "sum",
                //     render: (text, render) => {
                //         return text
                //     }
                // },
                {
                    title: "登记人",
                    dataIndex: "userName",
                    key: "userName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "审批人",
                    dataIndex: "checkName",
                    key: "checkName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "审批时间",
                    dataIndex: "checkedTime",
                    key: "checkedTime",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text, render) => {
                        let obj = status.find(item => item.value == text);
                        return obj === undefined ? '' : obj.label
                    }
                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:stockCheck:view']} onClick={() => this.opreate('normal', render.id)}>查看详情</TheButton>
                            {
                                render.status === 0 &&
                                <TheButton haspermi={['storage:stockCheck:edit']} onClick={() => this.opreate('edit', render.id)}>编辑</TheButton>

                            }
                            {
                                render.status === 1 ?
                                    <TheButton haspermi={['storage:stockCheck:execute']} onClick={() => this.opreate('execute', render.id)}>审核</TheButton> : null
                            }
                            {
                                render.status === 0 && <TheButton haspermi={['storage:stockCheck:del']} onClick={() => this.del(render.id)} >删除</TheButton>
                            }

                        </div>
                    }
                },
            ],
            newColumns_check: [],
            form_show_check: true,
            searchOption_check: [
                { field: 'code', label: '盘点单号', placeholder: '盘点单号', required: false, rules: [], type: 'Input', defaultValue: '' },

                { field: 'libraryName', label: '仓库名称', placeholder: '仓库名称', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
                { field: 'status', label: '状态', placeholder: '状态', required: false, rules: [], type: 'Select', options: status, defaultValue: '' },
            ],
            queryForm_check: {},
            dataSourceCheck: [],
            totalCheck: 0,
            totalStore: 0,
            libraryName_check: '',
            goodsName_store: '',
            libraryId_store: '',
            librarys: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            pageDataCheck: {
                pageNo: 1,
                pageSize: 10

            },
        }
    }
    componentDidMount() {
        this.setState({
            newColumns_check: this.state.columnsCheck,
            newColumns_store: this.state.columns
        })
        let searchParams = store.getState().searchValue
        let { queryForm_store, queryForm_check, pageNo, pageSize, pageNoC, pageSizeC, pathName } = searchParams
        let tabParams = store.getState().pageTabValue
        if (tabParams) {
            let { tab } = tabParams
            this.setState({
                defaultActiveKey: tab
            }, () => {
                if (tab === '1' && searchParams) {
                    this.queryFormRef_store.onSetDefault({
                        ...queryForm_store
                    })
                } else if (tab === '2' && searchParams) {
                    this.queryFormRef_check.onSetDefault({
                        ...queryForm_check
                    })
                }
            })
        }


        if (searchParams&&pageNo && pathName == 'stock') {
            this.setState({
                queryForm_check,
                queryForm_store,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                },
                pageDataCheck: {
                    pageNo: pageNoC, pageSize: pageSizeC
                }

            }, () => {
                this.getLibrarys()
                this.getCheckPage()
                this.getPage()
            })
        } else {
            this.getLibrarys()
            this.getCheckPage()
            this.getPage()
        }




    }
    goGoods(id) {
        this.props.history.push('/storageManager/goodsStore/' + id)
    }
    opreate(type, id) {
        this.props.history.push('/storageManager/takeStock/' + id + "/" + type)
    }
    async getLibrarys() {
        let res = await apiStockTakeListAddBefore()
        if (res.code === 0) {
            this.state.searchOption_store[0].options = res.data.librarys
            this.setState({
                librarys: res.data.librarys,
                searchOption_store: this.state.searchOption_store
            })
        }
    }
    // 库存
    getPage(values) {
        this.setState({
            queryForm_store: values === undefined ? this.state.queryForm_store : { ...values }
        }, async () => {

            let { pageNo, pageSize } = this.state.pageData
            let params = {
                pageNoC: this.state.pageDataCheck.pageNo,
                pageSizeC: this.state.pageDataCheck.pageSize,
                pageNo: this.state.pageData.pageNo,
                pageSize: this.state.pageData.pageSize,
                queryForm_store: this.state.queryForm_store,
                queryForm_check: this.state.queryForm_check,

            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'stock',
                    ...params
                }
            })
            let res = await apiStockLibraryGoodsPage({ pageNo, pageSize, ...this.state.queryForm_store })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    totalStore: res.totalCount
                })
            }
        })

    }
    // 盘点
    getCheckPage(values) {
        this.setState({
            queryForm_check: values === undefined ? this.state.queryForm_check : { ...values }
        }, async () => {
            let { pageNo, pageSize } = this.state.pageDataCheck
            let params = {
                pageNoC: this.state.pageDataCheck.pageNo,
                pageSizeC: this.state.pageDataCheck.pageSize,
                pageNo: this.state.pageData.pageNo,
                pageSize: this.state.pageData.pageSize,
                queryForm_store: this.state.queryForm_store,
                queryForm_check: this.state.queryForm_check,
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'stock',
                    ...params
                }
            })
            let res = await apiStockTakeListPage({ pageNo, pageSize, ...this.state.queryForm_check })
            if (res.code === 0) {
                this.setState({
                    dataSourceCheck: res.data,
                    totalCheck: res.totalCount
                })
            }
        })

    }

    pageChangeCheck = (pageNo, pageSize) => {
        this.setState({
            // libraryName_check: values.libraryName?values.libraryName:null,
            pageDataCheck: {
                pageNo, pageSize
            }
        }, () => {
            this.getCheckPage()
        })
    };
    pageChangeStore = (pageNo, pageSize) => {

        this.setState({
            // goodsName_store: values.goodsName ? values.goodsName : '',
            // libraryId_store: values.libraryId ? values.libraryId : '',
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getPage()
        })
    };
    onReset_check = () => {
        this.setState({
            queryForm_check: {}
        }, () => {

            this.pageChangeCheck(1, 10)
        })
    }
    onReset_store = () => {
        this.setState({
            queryForm_store: {}
        }, () => {
            this.pageChangeStore(1, 10)
        })
    }

    async del(id) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockTakeListDel({ id })
                if (res.code === 0) {
                    this.pageChangeCheck(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });

    }
    onFinishCheck = () => {
        let values = this.formRef_check.current.getFieldsValue()
        this.setState({
            libraryName_check: values.libraryName ? values.libraryName : '',

        }, () => {
            this.pageChangeCheck(1, 10)

        })
    }
    onFinishStore = () => {
        let values = this.formRef_store.current.getFieldsValue()
        this.setState({
            goodsName_store: values.goodsName ? values.goodsName : '',
            libraryId_store: values.libraryId ? values.libraryId : '',

        }, () => {
            this.pageChangeStore(1, 10)
        })

    }
    export = async () => {
        let tH_data, tB_data
        tH_data = [
            { prop: 'libraryName', title: '仓库名称' },
            { prop: 'goodsSkuNo', title: '物品编码' },
            { prop: 'goodsName', title: '物品名称' },
            { prop: 'sku', title: '规格' },
            { prop: 'minCount', title: '库存下限' , valueType:'number'},
            { prop: 'count', title: '库存量' , valueType:'number'},
            { prop: 'waiteOutCount', title: '待出库', valueType:'number' },
        ]
        let values = this.formRef_store.current.getFieldsValue()
        let res = await apiStockLibraryGoodsList({ "goodsName": values.goodsName ? values.goodsName : '', libraryId: values.libraryId ? values.libraryId : '' })
        if (res.code === 0 && res.data && res.data.length > 0) {
            tB_data = res.data.map(item => {
                return {
                    ...item,
                    minCount: item.minCount == -1 ? '不限制' : item.minCount,
                    row_bgColor: item.count < item.minCount ? '#e8b300' : ''
                }
            })
            exportSheetTable({
                fileName: '库存管理', tH_data, tB_data: tB_data, isSheet: true, merge: false
            })
        }

    }
    rowClassName(record, index) {

        if (record.minCount > record.count) {
            return 'warning'
        }
        return ''
    }
    onChange(e) {
        let params = {
            tab: e
        }
        store.dispatch({
            type: 'SavePageTabValue',
            data: {
                ...params
            }
        })

        this.setState({
            defaultActiveKey: e
        }, () => {
            if (e === '1') {
                this.queryFormRef_store.onSetDefault({
                    ...this.state.queryForm_store
                })
            } else {
                this.queryFormRef_check.onSetDefault({
                    ...this.state.queryForm_check
                })
            }
        })
    }

    render() {
        let {
            columns, dataSource, pageData, defaultActiveKey, columnsCheck,
            librarys, dataSourceCheck, pageDataCheck, totalCheck, totalStore,
            form_show_store, searchOption_store, newColumns_store,
            form_show_check, searchOption_check, newColumns_check

        } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                <Tabs activeKey={defaultActiveKey} type="card" size={'small'} onChange={(e) => this.onChange(e)}>

                    <TabPane tab="库存管理" key="1">
                        {/* <Form layout={'inline'}

                            ref={this.formRef_store} onFinish={() => this.onFinishStore()} style={{ marginBottom: 12 }}>
                            <Form.Item name={"goodsName"}>
                                <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"物品名称"} />
                            </Form.Item>
                            <Form.Item initialValue={undefined} name={"libraryId"}>
                                <Select placeholder={"请选择仓库"} style={{ width: 140 }}>
                                    {librarys.length > 0 && librarys.map(item => {
                                        return <Option value={item.id}>{item.name}</Option>
                                    })}
                                </Select>
                            </Form.Item>
                            <Form.Item>
                                <Space size="small" style={{ marginLeft: 10 }}>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                    <Button onClick={this.resetStore}>重置</Button>
                                    <TheButton type="default" size="middle" haspermi={['storage:stockStore:export']} onClick={this.export}>库存导出</TheButton>
                                </Space>
                            </Form.Item>
                        </Form> */}
                        <TheQueryForm ref={(ref) => this.queryFormRef_store = ref} show={form_show_store} option={searchOption_store}
                            onReset={() => this.onReset_store()}

                            onGetValues={(values) => this.getPage(values)} >
                        </TheQueryForm>
                        <TheTableExtend
                            columns={columns}
                            onFormTrigger={() => this.setState({ form_show_store: !this.state.form_show_store })}
                            onTableRefresh={() => this.getPage()}
                            onColumnsFilter={(value) => this.setState({
                                newColumns_store: value
                            })}
                        >
                            <TheButton type="default" size="middle" haspermi={['storage:stockStore:export']} onClick={this.export}>库存导出</TheButton>
                        </TheTableExtend>
                        <TheTable
                            scroll={{ x: "max-content", y: '63vh' }}
                            columns={newColumns_store}
                            rowClassName={(record, index) => this.rowClassName(record, index)}
                            dataSource={dataSource}
                        />
                        <ThePagination
                            pageNo={pageData.pageNo}
                            pageSize={pageData.pageSize}
                            total={totalStore}
                            pageChange={this.pageChangeStore}
                        />
                    </TabPane>


                    <TabPane tab="库存盘点" key="2">
                        {/* <Form layout={'inline'} ref={this.formRef_check} onFinish={() => this.onFinishCheck()} style={{ marginBottom: 12 }}>
                            <Form.Item name={"libraryName"}>
                                <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"仓库名称"} />
                            </Form.Item>

                            <Form.Item>
                                <Space size="small" style={{ marginLeft: 10 }}>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                    <Button onClick={this.resetCheck}>重置</Button>
                                </Space>
                            </Form.Item>
                        </Form>
                        <div style={{ marginBottom: 12 }}>
                            <TheButton haspermi={['storage:stockCheck:add']} size="middle" onClick={() => this.props.history.push('/storageManager/takeStock/null/add')} type="primary">新增</TheButton>
                        </div> */}
                        <TheQueryForm ref={(ref) => this.queryFormRef_check = ref} show={form_show_check} option={searchOption_check}
                            onReset={() => this.onReset_check()}
                            onGetValues={(values) => this.getCheckPage(values)} >
                        </TheQueryForm>
                        <TheTableExtend
                            columns={columnsCheck}
                            onFormTrigger={() => this.setState({ form_show_check: !this.state.form_show_check })}
                            onTableRefresh={() => this.getCheckPage()}
                            onColumnsFilter={(value) => this.setState({
                                newColumns_check: value
                            })}
                        >
                            <TheButton haspermi={['storage:stockCheck:add']} size="middle" onClick={() => this.props.history.push('/storageManager/takeStock/null/add')} type="primary">新增</TheButton>

                        </TheTableExtend>
                        <TheTable
                            scroll={{ x: "max-content", y: '63vh' }}
                            columns={newColumns_check}
                            dataSource={dataSourceCheck}
                        />
                        <ThePagination
                            pageNo={pageDataCheck.pageNo}
                            pageSize={pageDataCheck.pageSize}
                            total={totalCheck}
                            pageChange={this.pageChangeCheck}
                        />
                    </TabPane>

                </Tabs>


            </div >
        );
    }
}
export default Stock
